package cn.wen233.srpc.core.server.handletask;

import cn.wen233.srpc.basic.model.Request;
import cn.wen233.srpc.basic.model.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * Java原生序列化方式
 *
 * @author wenei
 * @date 2021-10-29 11:42
 */
public class NativeSerializeTask extends AbstractTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(NativeSerializeTask.class);

    private Socket clientSocket;

    public NativeSerializeTask(Socket socket) {
        this.clientSocket = socket;
    }

    @Override
    public void run() {
        try {
            // 采用ObjectInputStream原生方式进行反序列化
            Request request = (Request) new ObjectInputStream(clientSocket.getInputStream()).readObject();

            Response response = SERVER_EXECUTOR.execute(request);

            final ObjectOutputStream objectOutputStream = new ObjectOutputStream(clientSocket.getOutputStream());
            objectOutputStream.writeObject(response);
            LOGGER.info("{}:{} 请求执行{}.{}方法", clientSocket.getInetAddress(), clientSocket.getPort(), request.getServiceName(), request.getMethodName());
            clientSocket.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
